package com.mccormick.dominosa.database;

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

// source - http://www.codeproject.com/Articles/119293/Using-SQLite-Database-with-Android

public class DatabaseHelper extends SQLiteOpenHelper{

	// Database Name
	private static final String dbName = "dominosaDB";
	
	// Puzzle table
	private static final String tablePuzzles = "Puzzles";
	private static final String colPuzzleID = "PuzzleID";
	private static final String colNumRows = "NumRows";
	private static final String colGrid = "Grid";
	
	/**
	 * Constructor
	 * @param context
	 * @param factory
	 * @param version
	 */
	public DatabaseHelper(Context context, CursorFactory factory, int version) {
		super(context, dbName, factory, version);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		
		// Creates the Table Puzzles
		db.execSQL("CREATE TABLE " + tablePuzzles
						+ "( " + colPuzzleID + "INTEGER PRIMARY KEY AUTOINCREMENT, "
						+ colNumRows + "INTEGER, "
						+ colGrid + "TEXT);");
		
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// TODO Auto-generated method stub
		
	}
	
	/**
	 * Add foreign key constraints
	 */
	@Override
	public void onOpen(SQLiteDatabase db) {
		super.onOpen(db);
		if (!db.isReadOnly()) {
			// Enable foreign key constraints
			db.execSQL("PRAGMA foreign_keys=ON;");
		}
	}
	 
	/**
	 * Inserts a record into the Table Puzzles 
	 * 
	 * @param numRows
	 * @param grid
	 */
	public void insertPuzzle(String numRows, String grid)
	{
		// Get a database
		SQLiteDatabase db = this.getWritableDatabase();
		
		// build the row to input
		ContentValues cv = new ContentValues();
		cv.put(colNumRows, numRows);
		cv.put(colGrid, grid);
		
		// insert
		db.insert(tablePuzzles, colPuzzleID, cv);
		
		// done. close
		db.close();
	}

}
